package com.easycms.framework.web;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.easycms.common.LoggerHelper;
import com.easycms.constant.CookieConstants;
import com.easycms.framework.shiro.UserOwnInfo;
import org.omg.CORBA.UNKNOWN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import sun.swing.StringUIClientPropertyKey;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * @author yushuo
 * @className
 * @descripton TODO
 * @date 2021/2/2 9:43
 **/

@Component
public class RequestHelper {

    /**
     * 定义移动端请求的所有可能类型
     */
    private final String[] agent = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP1 = "127.0.0.1";
    @Autowired
    HttpServletRequest httpServletRequest;


    /**
    *
     * @author yushuo
     * @description //获取请求参数 String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
    **/
    public String getString(String key,String defaultValue){
         String param= httpServletRequest.getParameter(key);
         if(!StrUtil.isEmpty(param)){
             return param.trim();
         }
         return defaultValue.trim();
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 Integer
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public Integer getInt(String key,Integer defaultValue){
        String param= httpServletRequest.getParameter(key);
        if(!StrUtil.isEmpty(param)){
            return Convert.toInt(param.trim(),defaultValue);
        }
        return defaultValue;
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 Long
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public Long getInt64(String key,Long defaultValue){
        String param= httpServletRequest.getParameter(key);
        if(!StrUtil.isEmpty(param)){
            return Convert.toLong(param.trim(),defaultValue);
        }
        return defaultValue;
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 String[]
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String[] getStringArray(String key){
        String[] param= httpServletRequest.getParameterValues(key);
        if(param==null||param.length==0){
            return new String[]{};
        }
        return param;
    }

    /**
     *
     * @author yushuo
     * @description //获取Cookie String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String getCookie(String cookieKey){
        String cookieValue=null;
        for (Cookie cookie : httpServletRequest.getCookies()) {
            if (cookieKey.equals(cookie.getName())) {
                try {
                   // LoggerHelper.console("原始cookie："+cookie.getValue());
                    cookieValue=URLDecoder.decode(cookie.getValue(), "UTF-8");
                    //LoggerHelper.console("原始解析后："+cookieValue);
                } catch (UnsupportedEncodingException e) {
                    break;
                }
                break;
            }
        }
        return cookieValue;
    }

    /**
    *
     * @author yushuo
     * @description 获取用户登录信息
     * @date 11:05 2021/2/24
     * @param []
     * @return com.easycms.framework.shiro.UserOwnInfo
    **/
    public UserOwnInfo getUserOwnInfo(){

        String userCookie=getCookie(CookieConstants.LOGIN_COOKIE_NAME);
        if(StrUtil.isEmpty(userCookie)){
            return null;
        }

        return  JSONUtil.toBean(userCookie,UserOwnInfo.class);
    }

    /**
     *
     * @author yushuo
     * @description //获取Header String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String getHeader(String key,String defaultValue){
        String headerValue= httpServletRequest.getHeader(key);
        if(!StrUtil.isEmpty(headerValue)){
            return headerValue.trim();
        }
        return defaultValue.trim();
    }

    public String getContextPath(){
        return httpServletRequest.getContextPath();
    }


    /**
    *
     * @author yushuo
     * @description //获取所有参数
     * @date 16:33 2021/2/4
     * @param []
     * @return java.util.Map<java.lang.String,java.lang.String[]>
    **/
    public Map<String, String[]> getAll() {
        return httpServletRequest.getParameterMap();
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param
     */
    public boolean isAjaxRequest() {
        String accept = httpServletRequest.getHeader("accept");
        if (accept != null && accept.indexOf("application/json") != -1) {
            return true;
        }

        String xRequestedWith = httpServletRequest.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
            return true;
        }

        String uri = httpServletRequest.getRequestURI();
        if (StrUtil.containsAnyIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }

        String ajax = httpServletRequest.getParameter("__ajax");
        if (StrUtil.containsAnyIgnoreCase(ajax, "json", "xml")) {
            return true;
        }
        return false;
    }

    /**
     * 判断User-Agent 是不是来自于手机
     */
    public boolean isMobile(String ua) {
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
    *
     * @author 获取用户ip
     * @description //TODO
     * @date 11:31 2021/3/1
     * @param []
     * @return java.lang.String
    **/
    public  String getIp(){
        String ip = LOCALHOST_IP1;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
            ip = httpServletRequest.getHeader("X-Original-Forwarded-For");
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("X-Forwarded-For");
            }
            //获取nginx等代理的ip
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("x-forwarded-for");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("Proxy-Client-IP");
            }
            if (StrUtil.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("HTTP_CLIENT_IP");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getHeader("HTTP_X_FORWARDED_FOR");
            }
            //兼容k8s集群获取ip
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = httpServletRequest.getRemoteAddr();
                if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                    //根据网卡取本机配置的IP
                    InetAddress iNet = null;
                    try {
                        iNet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                       return LOCALHOST_IP1;
                    }
                    ip = iNet.getHostAddress();
                }
            }
        } catch (Exception e) {
            return LOCALHOST_IP1;
        }
        //使用代理，则获取第一个IP地址
        if (!StrUtil.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }

        return ip;
    }

}
